﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveMagicBall : MonoBehaviour
{
    public List<Vector3> nodes;
    public Vector3[] directions;
    private ParticleSystem particles;

    void Start()
    {
        //设置粒子生命期
        ParticleSystem ps = GetComponent<ParticleSystem>();
        ParticleSystem.MainModule main = ps.main;
        main.startLifetime = nodes.Count;

        if (nodes.Count == 0)
        {
            Debug.LogError("请添加至少1个路径点node");
        }
            
        //根据路径点获得每一路径段的方向向量
        directions = new Vector3[nodes.Count];
        for (int i = 0; i < nodes.Count; i++)
        {
            if (i - 1 >= 0)
            {
                directions[i] = nodes[i] - nodes[i - 1];
            }
            else
            {
                directions[i] = nodes[i] - transform.position;
            }
        }   
    }

    void Update()
    {
        particles = GetComponent<ParticleSystem>();
        ParticleSystem.Particle[] particleList = new ParticleSystem.Particle[particles.particleCount];
        int particleCount = particles.GetParticles(particleList);

        for (int i = 0; i < particleCount; i++)
        {
            float timeALive = particleList[i].startLifetime - particleList[i].remainingLifetime;            //计算粒子当前的生命
            float dist = GetAddedMagnitude((int)timeALive);         //根据粒子生命确定粒子已经过路径段
            int count = 0;
            
            //判断粒子所在路径段
            while (dist > GetAddedMagnitude(count))
            {
                count++;
                particleList[i].velocity = directions[count];       //设置粒子移动速度
            }
        }
        particles.SetParticles(particleList, particleCount);
    }

    //获得路径长度
    private float GetAddedMagnitude(int count)
    {
        float addedMagnitude = 0;
        for (int i = 0; i < count; i++)
        {
            addedMagnitude += directions[i].magnitude;
        }
        return addedMagnitude;
    }
}